<?php

namespace app\api\service;

use app\model\MicroStory;
use app\model\Stills;
use app\model\Applet;
use think\facade\Cache;

class InfoService
{
    private $microStoryModel;
    private $stillsModel;
    private $appletModel;

    public function __construct(MicroStory $microStoryModel, Stills $stillsModel, Applet $appletModel)
    {
        $this->microStoryModel = $microStoryModel;
        $this->stillsModel = $stillsModel;
        $this->appletModel = $appletModel;
    }

    // 获取微故事列表
    public function getMicroStoryList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 30;

        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.api_get_micro_story_list').$page;
        $redis->select(7);
        $data = $redis->get($key);

        if (empty($data)) {
            $where = [
                'is_release' => 1
            ];

            $data = $this->microStoryModel->getPagingDataByWhere($where, $page, $limit, 'id, title, cover, author, created_at');
            $redis->set($key, json_encode($data), 86400);
        } else {
            $data = json_decode($data, true);
        }

        return $data;
    }

    // 获取微故事详情
    public function getMicroStoryDetail($id)
    {
        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.api_get_micro_story_detail').$id;
        $redis->select(7);
        $data = $redis->get($key);

        if (empty($data)) {
            $data = $this->microStoryModel->getInfoByWhere(['id' => $id], 'id, title, cover, author, content, created_at');
            $redis->set($key, json_encode($data), 86400);
        } else {
            $data = json_decode($data, true);
        }

        return $data;
    }

    // 获取剧照列表
    public function getStillsList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 30;

        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.api_get_stills_list').$page;
        $redis->select(7);
        $data = $redis->get($key);

        if (empty($data)) {
            $data = $this->stillsModel->getPagingDataByWhere([], $page, $limit, 'id, cover', 'sort desc');
            $redis->set($key, json_encode($data), 86400);
        } else {
            $data = json_decode($data, true);
        }

        return $data;
    }
}